<template>
  <md-page title="报名详情" isBtn :btnTextItems="data.btnTextItems" @btnClick="bottomBtnClick">
    <uni-notice-bar
      v-if="data.formData.invite_code"
      single
      :text="`邀请码：${data.formData.invite_code} (点击复制)`"
      @click="handleInviteCode" />
    <uni-notice-bar
      v-if="
        data?.formData?.user_button_state >= TeamUserButtonState.查看详情 && data.formData?.template_code === 'team'
      "
      single
      color="#fff"
      background-color="#D92121"
      text="摇号状态 >>"
      moreColor="#fff"
      show-get-more
      :more-text="data.formData?.is_true > 0 ? (data.formData.is_true == 1 ? '已中签' : '未中签') : '未开始'" />
    <uni-forms ref="form" :modelValue="data.formData" :rules="data.rules" label-position="top" label-width="100">
      <view class="container">
        <view class="form-item-wrap" v-show="data.formData.header_truename">
          <view class="form-label">队长名称</view>
          <text class="form-item" selectable user-select>
            {{ data.formData.header_truename }}
          </text>
        </view>
        <view
          class="form-item-wrap"
          v-show="data.formData.header_mobile"
          @click="() => handleTell(data.formData.header_mobile)">
          <view class="form-label">队长联系电话</view>
          <text class="form-item" selectable user-select>
            {{ data.formData.header_mobile }}
          </text>
        </view>

        <view class="form-item-wrap" v-if="data.formData.sign_num">
          <view class="form-label">报名人数</view>
          <text class="form-item" selectable user-select>
            {{ data.formData.sign_num }}
          </text>
        </view>

        <template v-for="item in data.allowFields" :key="item.field_name">
          <view class="form-item-wrap" v-if="!['contact', 'contact_mobile'].includes(item.field_name)">
            <template v-if="item.field_type !== 'image'">
              <view class="form-label">{{ item.field_label }}</view>
              <text class="form-item" selectable user-select>
                <text v-if="item.field_type === 'radio'">
                  {{
                    item.field_name === 'sex'
                      ? data.formData[item.field_name] == '1'
                        ? '男'
                        : '女'
                      : data.formData[item.field_name] == '1'
                      ? '是'
                      : '否'
                  }}
                </text>
                <template v-else>
                  {{ data.formData[item.field_type === 'select' ? item.field_name + '_name' : item.field_name] }}
                </template>
              </text>
            </template>
            <template v-if="item.field_type === 'image' && data.formData?.[item.field_name]">
              <view class="form-label">{{ item.field_label }}</view>
              <view class="form-item">
                <image :src="data.formData[item.field_name]" :style="{ width: '200rpx', height: '140rpx' }" />
              </view>
            </template>
          </view>
          <uni-forms-item v-else :label="item.field_label" :name="item.field_name" required>
            <uni-easyinput
              :type="item.field_name === 'contact' ? 'text' : 'number'"
              v-model="data.formData[item.field_name]"
              placeholder="请输入"
              :input-border="false" />
          </uni-forms-item>
        </template>

        <!-- 绑定的成员 -->
        <view class="card" v-show="data.formData.member_list?.length > 0">
          <view class="forms-item-label">成员</view>
          <view class="form-item-content">
            <view class="member-list">
              <view class="member-item" v-for="item in data.formData.member_list" :key="item.id">
                <!-- <view class="del-btn">
                  <md-icon name="delete" width="31" height="31" @click="del(item.id)" />
                </view> -->
                <view v-for="field in data.memberList" :key="field.name">
                  {{
                    field.name === 'sex'
                      ? item[field.name] == 1
                        ? '男'
                        : '女'
                      : field.name === 'age'
                      ? item[field.name] + '岁'
                      : item[field.name]
                  }}
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </uni-forms>

    <!-- 邀请队员图片分享弹窗 -->
    <uni-popup ref="dialog" type="dialog">
      <view class="popup-content">
        <view class="image">
          <image :src="shareImage" mode="widthFix" />
        </view>
        <view class="bottom-btn" @click="hanleSaveImage">保存图片到相册</view>
      </view>
    </uni-popup>
  </md-page>
</template>

<script setup lang="ts">
import { onLoad, onShareAppMessage } from '@dcloudio/uni-app';
import { reactive, ref } from 'vue';
// 接口
import {
  signTeamApplyQuit,
  signTeamDelMember,
  signTeamDetail,
  signTeamUpdateInfo,
  signTeamShare,
  apply_compete,
} from '@/api';
import type { BtnTextItem } from '@/components/md-ui/components/md-page/md-page.vue';
import { parseParams, stringifyParams, Toast } from '@/utils/util';
import type { SignTeam } from '@/api/data';
import { fromType, TeamUserButtonState, UserButtonState } from '@/api/enum';
import { cancelPayOrder, payOrder } from '@/utils/api';

const data = reactive<any>({
  active_id: -1,
  sign_team_id: -1,
  active_state: 1,
  shareTitle: '邀请队员参加',
  invateShareImg: '', // 邀请队员的分享图片
  allowFields: [], // 动态显示的字段
  formData: {},
  rules: {
    size: {
      rules: [
        {
          required: true,
          errorMessage: '请选择服装尺寸',
        },
      ],
    },
    contact: {
      rules: [
        {
          required: true,
          errorMessage: '请输入紧急联系人',
        },
      ],
    },
    contact_mobile: {
      rules: [
        {
          required: true,
          errorMessage: '请输入紧急联系人电话',
        },
      ],
    },
  },
  memberList: [
    { label: '姓名', name: 'truename' },
    { label: '性别', name: 'sex' },
    { label: '年龄', name: 'age' },
    { label: '电话', name: 'mobile' },
  ], // 成员添加
  btnTextItems: [], // 底部按钮集合
  idTypeList: [], // 证件类型下拉
  configInfo: {},
  is_pay: 0, // 是否待支付 0否 1是
});
const shareImage = ref('');
const dialog = ref(null);
// 判断是否是润无声引流
const isPageShare = ref(true);
// 判断邀请队员时是否使用润物无声的图片
const isShareImg = ref(false);
const form = ref(null);
const modalType = ref('');

const pageCb = () => {
  uni.navigateBack();
  // 返回的页面执行刷新
  uni.setStorageSync('isRefresh', 1);
};

const handleInviteCode = () => {
  uni.setClipboardData({
    data: data.formData.invite_code,
    success: function () {
      Toast('邀请码复制成功');
    },
  });
};

// 底部功能按钮回调
const bottomBtnClick = async (info: { item: BtnTextItem }) => {
  const { key } = info.item;
  // 支付
  if (key === 'pay') {
    payOrder(
      {
        order_id: data.formData.order_id || '',
        order_sn: data.formData.order_sn || '',
      },
      (type: 'success' | 'fail') => {
        const msg = type === 'success' ? '报名费用支付成功' : '用户取消支付';
        uni.showModal({
          title: '提示',
          content: msg,
          showCancel: false,
          success: res => {
            if (res.confirm) {
              fetchSignTeamDetail(data.formData);
            }
          },
        });
      }
    );
  }
  // 取消支付
  if (key === 'cancel_pay') {
    cancelPayOrder({
      order_id: data.formData.order_id || '',
      order_sn: data.formData.order_sn || '',
    });
  }
  // 退赛
  if (key === 'withdraw') {
    uni.showModal({
      title: '提示',
      content: '是否确定申请退赛？',
      success: res => {
        if (res.confirm) {
          fetchApplyCompete();
        }
      },
    });
  }
  // 提交编辑
  if (key === 'submit') {
    try {
      const vals = await form.value?.validate();
      uni.showModal({
        title: '提示',
        content: '是否提交编辑？',
        success: res => {
          if (res.confirm) {
            fetchSignTeamUpdateInfo({
              ...vals,
              sign_id: data.formData.sign_id,
            });
          }
        },
      });
    } catch (error) {}
  }
  // 解散队伍
  // if (key === 'disband') {
  //   uni.showModal({
  //     title: '提示',
  //     content: '是否确定解散队伍？',
  //     success: res => {
  //       if (res.confirm) {
  //         fetchSignTeamRemove();
  //       }
  //     },
  //   });
  // }
  // 队伍管理
  if (key === 'team_member') {
    uni.navigateTo({
      url: `/pages/registration/list?active_id=${data.active_id}&sign_team_id=${
        data.sign_team_id
      }&teamInfo=${JSON.stringify(data.formData)}`,
    });
  }
  // 队员申请退赛
  if (key == 'quit') {
    uni.showModal({
      title: '提示',
      content: '本操作将会把您报名时添加的成员一起移除！是否确定退出队伍？',
      success: res => {
        if (res.confirm) {
          fetchSignTeamApplyQuit();
        }
      },
    });
  }
  // 领取装备包 及 选择尺码
  if (key == 'bag_size') {
    const _params = stringifyParams({
      active_id: data.active_id,
      group: data.formData?.group || -1,
      size_id: data.formData?.size_id || '',
      user_button_state: data.formData?.user_button_state || '',
    });
    uni.navigateTo({
      url: `/pages/registration/bag?params=${_params}`,
    });
  }
  modalType.value = key || '';
  if (isShareImg.value) return;

  if (key === 'share') {
    fetchSignTeamShare();
  }
};

function del(id: number) {
  uni.showModal({
    title: '提示',
    content: '是否删除该成员？',
    success: res => {
      if (res.confirm) {
        fetchSignTeamDelMember(id + '');
      }
    },
  });
}

// 拨打手机号
const handleTell = (phone: string) => {
  if (!phone) return;
  uni.makePhoneCall({
    phoneNumber: phone,
  });
};

/**
 * 接口相关
 */
// 查看报名详情
const fetchSignTeamDetail = async (params?: Record<string, string>) => {
  try {
    const res = await signTeamDetail({
      sign_team_id: params?.sign_team_id || data.sign_team_id || '',
    });
    // 动态表单处理
    const allowFields = res?.data?.allow_fields;
    // const allowFields = res.data.is_header == 1 ? res?.data?.allow_fields || [] : res.data?.allow_fields?.filter(item => item.is_member_show == 1 || ['title', 'group'].includes(item.field_name)) || [];
    data.allowFields = allowFields;

    const leader = res?.data?.member_list.filter(item => item.is_main == '1') || [];
    const members = res?.data?.member_list.filter(item => item.is_main != '1') || [];
    data.formData = {
      ...data.formData,
      ...res?.data,
      ...leader?.[0],
      member_list: members,
    };
    data.shareTitle = data.formData.title + ' - ' + data.formData.sign_num;

    // 处理底部操作按钮
    // 是否为队长 is_header = 1
    const _is_header = res.data?.is_header == 1;
    // is_true = 1 (已中签)
    const _is_true = res.data?.is_true == 1;
    const template_code = res.data?.template_code;
    // 后台控制按钮样式
    let commonStyle = (type: number) => ({
      color: data.configInfo?.['button_color' + type] || '#1CA4C0',
      textColor: data.configInfo?.['button_color' + type + '_text'] || '#ffffff',
    });
    const user_button_state = res.data?.user_button_state;
    // 个人报名
    if (template_code === 'single') {
      data.btnTextItems = [
        {
          text: '去支付',
          key: 'pay',
          hide: user_button_state != UserButtonState.待支付,
          ...commonStyle(1),
        },
        {
          text: '取消支付',
          key: 'cancel_pay',
          hide: user_button_state != UserButtonState.待支付,
          ...commonStyle(2),
        },
        {
          text: '退赛',
          key: 'withdraw',
          hide: user_button_state != UserButtonState.申请退赛,
          ...commonStyle(1),
        },
      ];
    } else {
      // 选择尺码按钮文案
      const bag_size_title = [TeamUserButtonState.中签_已完成, TeamUserButtonState.领取参赛包].includes(
        user_button_state
      )
        ? '领取装备包'
        : user_button_state === TeamUserButtonState.中签_待支付
        ? '去支付'
        : '选择尺码';
      // 组队报名
      data.btnTextItems = [
        {
          text: '去支付',
          key: 'pay',
          hide: user_button_state != TeamUserButtonState.待支付,
          ...commonStyle(1),
        },
        {
          text: '取消支付',
          key: 'cancel_pay',
          hide: user_button_state != TeamUserButtonState.待支付,
          ...commonStyle(2),
        },
        {
          text: bag_size_title,
          key: 'bag_size',
          hide:
            ![
              TeamUserButtonState.选择尺码,
              TeamUserButtonState.中签_待支付,
              TeamUserButtonState.中签_已完成,
              TeamUserButtonState.领取参赛包,
            ].includes(user_button_state) || !_is_true,
          ...commonStyle(2),
        },
        //{
        //  text: '提交编辑',
        //  key: 'submit',
        //  hide: ![TeamUserButtonState.组队中, TeamUserButtonState.组队成功].includes(user_button_state) || _is_true,
        //  ...commonStyle(1),
        //},
        {
          text: '邀请队员',
          key: 'share',
          openType: isShareImg.value ? 'share' : undefined,
          hide: !_is_header || _is_true || ![TeamUserButtonState.组队中].includes(user_button_state),
          ...commonStyle(1),
        },
        {
          text: '队员管理',
          key: 'team_member',
          hide: ![TeamUserButtonState.组队中, TeamUserButtonState.组队成功].includes(user_button_state) || !_is_header,
          ...commonStyle(2),
        },
        {
          text: '退出队伍',
          key: 'quit',
          hide: _is_header || _is_true || user_button_state != TeamUserButtonState.组队中,
          ...commonStyle(1),
        },
      ];
    }
  } catch (error) {}
};

// 申请退赛
const fetchApplyCompete = async () => {
  try {
    const res = await apply_compete({ sign_id: data.formData.sign_id || '' });
    uni.showModal({
      title: '提示',
      content: res?.msg || '申请退赛成功',
      showCancel: false,
      success: res => {
        if (res.confirm) {
          uni.switchTab({ url: '/pages/index/index' });
        }
      },
    });
  } catch (e) {
    //TODO handle the exception
  }
};

// 绑定的成员删除
const fetchSignTeamDelMember = async (sign_id: string) => {
  try {
    await signTeamDelMember({ sign_id });
    Toast('删除成功');
    fetchSignTeamDetail({ sign_team_id: data.sign_team_id + '' });
  } catch (e) {
    //TODO handle the exception
  }
};

// 保存图片到相册
const hanleSaveImage = () => {
  // 下载网络图片
  uni.downloadFile({
    url: shareImage.value,
    success: function (res) {
      if (res.statusCode === 200) {
        // 保存图片到相册
        uni.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success: function () {
            Toast('图片已保存到相册');
            dialog.value?.close?.();
          },
        });
      } else {
        Toast('图片请求失败');
        // throw new Error('请求失败');
      }
    },
    fail: function (err) {
      console.error('图片下载失败::', err);
      Toast('图片下载失败');
      // throw new Error('图片下载失败');
    },
  });
};

// 队员申请退赛
const fetchSignTeamApplyQuit = async () => {
  try {
    const res = await signTeamApplyQuit({ sign_id: data.formData.sign_id });
    uni.showModal({
      title: '提示',
      content: res?.msg || '退赛成功',
      showCancel: false,
      success: res => {
        if (res.confirm) {
          pageCb();
        }
      },
    });
  } catch (e) {
    //TODO handle the exception
  }
};

// 报名修改
const fetchSignTeamUpdateInfo = async (params: SignTeam.UpdateInfo.Body) => {
  try {
    const res = await signTeamUpdateInfo(params);
    uni.showModal({
      title: '提示',
      content: res?.msg || '修改成功',
      showCancel: false,
      success: res => {
        if (res.confirm) {
          pageCb();
        }
      },
    });
  } catch (error) {}
};

// share-image
const fetchSignTeamShare = async () => {
  uni.showLoading({
    title: '加载中...',
  });
  try {
    if (!shareImage.value) {
      const res = await signTeamShare({
        sign_team_id: data.sign_team_id,
      });
      shareImage.value = res.data;
    }
    // 打开弹窗
    dialog.value?.open?.();
  } catch (e) {
    //TODO handle the exception
  }
  uni.hideLoading();
};

onLoad(option => {
  const configInfo = uni.getStorageSync('configInfo') ? JSON.parse(uni.getStorageSync('configInfo')) : '';
  if (configInfo) {
    data.configInfo = configInfo;
    // is_sync_rwws 1同步 0不同步
    isPageShare.value = !Number(configInfo.is_sync_rwws);
    isShareImg.value = !Number(configInfo.is_sync_share_rwws);
  }
  // 在目标页面中获取数据
  const cacheImge = uni.getStorageSync('shareImg');
  if (cacheImge) {
    data.invateShareImg = cacheImge;
  }

  const params = parseParams(option?.params);
  data.active_id = params?.active_id;
  data.sign_team_id = params?.sign_team_id;
  data.is_pay = params?.pay || 0;
  data.active_state = params?.active_state ? Number(params.active_state) : undefined;
  fetchSignTeamDetail(params);
  uni.showShareMenu({
    withShareTicket: true,
    menus: ['shareAppMessage', 'shareTimeline'],
  });
});

// 分享钩子
onShareAppMessage(res => {
  // 传递的参数
  const _params = stringifyParams({
    type: 'member',
    active_id: data?.active_id,
    invite_code: data.formData.invite_code,
    sign_team_id: data?.sign_team_id,
    from: fromType.分享,
  });
  return {
    title: data.shareTitle,
    imageUrl: data.invateShareImg,
    path: `/pages/registration/index?params=${_params}`,
  };
});
</script>

<style lang="scss" scoped>
.container {
  padding: 0 30rpx 30rpx;
  & > view {
    margin-bottom: 20rpx;
  }
  // 报名信息
  .form-item-wrap {
    .form-label {
      height: 36px;
      line-height: 36px;
      padding-bottom: 10px;
      font-size: 14px;
      color: #606266;
    }
    .form-item {
      display: block;
      background: white;
      border-radius: 10rpx;
      padding: 30rpx 20rpx;
    }
  }
  // 队员信息样式
  .forms-item-label {
    height: 36px;
    line-height: 36px;
    padding-bottom: 10px;
    font-size: 14px;
    color: #606266;
  }
  .form-item {
    background: white;
    border-radius: 10rpx;
    padding: 10rpx 0 10rpx 10px;
  }
  .form-item-content {
    padding: 16rpx;
    background: white;
  }
  .form-item-row {
    position: relative;
    .del-button {
      position: absolute;
      right: 0;
      top: 0;
    }
  }
  .member-list {
    .del-btn {
      position: absolute;
      top: 0;
      right: 0;
    }
    .member-item {
      position: relative;
      width: 100%;
      height: 80rpx;
      background: #f7f7f7;
      border-radius: 10rpx;
      font-size: 28rpx;
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 0 24rpx;
      box-sizing: border-box;
      &:not(:last-of-type) {
        margin-bottom: 20rpx;
      }
    }
  }
  .add {
    width: 100%;
    height: 80rpx;
    line-height: 80rpx;
    background: #f7f7f7;
    border-radius: 10rpx;
    color: #b3b3b3;
    font-size: 28rpx;
    text-align: center;
  }
}
// 弹窗相关样式
.popup-content {
  @mixin flex-l-c {
    display: flex;
    flex-direction: column;
    align-items: center;
  }
  @mixin flex-l-c {
    display: flex;
    flex-direction: column;
    align-items: center;
  }
  @include flex-l-c;
  padding: 15px;
  height: 500rpx;
  background-color: #fff;
}
</style>
